package com.zh.view.pane

import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Attachment
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.FolderOpen
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.awt.ComposeWindow
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.zh.mycommon.util.Fnv32aHash
import com.zh.filetransport.contrl.CommandAdd
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.swing.Swing
import kotlinx.coroutines.withContext
import com.zh.view.FileDataItem
import com.zh.view.component.TopBar
import com.zh.view.data.AppStore
import com.zh.view.data.ElMessage
import com.zh.view.data.SendTaskStore
import java.awt.FileDialog
import java.awt.Frame
import java.awt.datatransfer.DataFlavor
import java.awt.dnd.*
import java.io.File

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FileSelectorDialogExample(window: ComposeWindow) {
    var showDialog by remember { mutableStateOf(false) }
    val selectedFiles = remember { mutableStateListOf<File>() }

    val component = window.contentPane.components.getOrNull(0)

    // 设置文件拖放处理
    LaunchedEffect(Unit) {
        val dropTarget = object : DropTargetAdapter() {
            override fun dragEnter(event: DropTargetDragEvent) {
                if (event.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                    event.acceptDrag(DnDConstants.ACTION_COPY)
                }
            }

            override fun drop(event: DropTargetDropEvent) {
                if (event.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                    event.acceptDrop(DnDConstants.ACTION_COPY)
//                    println("drop ... ")
                    val files = event.transferable
                        .getTransferData(DataFlavor.javaFileListFlavor) as List<File>

                    files.forEach {
                        if (!selectedFiles.contains(it)) {
                            selectedFiles.add(it)
//                            println("已选择文件 " + it.path)
                        }
                    }
                    event.dropComplete(true)
                }
            }
        }
        // 设置窗口为拖放目标
        DropTarget(component, DnDConstants.ACTION_COPY, dropTarget, true)
    }
// ✅ 在组件销毁时解绑
    DisposableEffect(Unit) {
        onDispose {
            component?.dropTarget = null // 解绑拖放目标
        }
    }

    Column {
        TopBar("创建任务")

        Column(
            modifier = Modifier.fillMaxSize().padding(
                start = 16.dp,
                end = 16.dp,
                bottom = 16.dp
            )
        ) {
            // 选择文件按钮
            Button(
                onClick = { showDialog = true },
                modifier = Modifier.fillMaxWidth(),
                colors = ButtonDefaults.filledTonalButtonColors()
            ) {
                Icon(Icons.Default.FolderOpen, contentDescription = null)
                Spacer(modifier = Modifier.width(8.dp))
                Text("选择文件")
            }

            // 显示已选择的文件
            if (selectedFiles.isNotEmpty()) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically  // 关键：垂直居中
                ) {
                    Text("已选择的文件", fontWeight = FontWeight.Medium, fontSize = 16.sp)
                    // 关键：Spacer 占据剩余空间，将 Button 推到右侧
                    Spacer(modifier = Modifier.weight(1f))
                    Button(
                        onClick = {
                            if (AppStore.peerIp.value.isEmpty()) {
                                ElMessage.warn("未连接RemoteIP")
                                return@Button
                            }

                            selectedFiles.forEach({
                                val task = FileDataItem(
                                    Fnv32aHash.hash(it.path).toString(),
                                    it.name,
                                    it.length(),
                                    it.isDirectory
                                )
                                CommandAdd(it.path, task.id) //调用TCP发送命令
                                SendTaskStore.addItem(task)
                            })

                            selectedFiles.clear()
                        },
                        modifier = Modifier.padding(end = 8.dp)
                    ) {
                        Text("确认")
                    }
                }
                Spacer(modifier = Modifier.height(4.dp))

                // 修复：使用单一的LazyColumn而不是嵌套滚动组件
                LazyColumn(
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(max = 300.dp)
                        .border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(8.dp))
                        .padding(8.dp)
                ) {
                    items(selectedFiles) { file ->
                        FileItem(
                            file = file,
                            onRemove = { selectedFiles.remove(file) }
                        )

                        // 关键修改：只在不是最后一项时显示分隔线
                        if (file != selectedFiles.lastOrNull()) {
                            HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
                        }
                    }
                }
            } else if (showDialog.not()) {
                // 空状态提示
                Spacer(modifier = Modifier.height(10.dp))
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .fillMaxHeight()
                        .border(
                            2.dp,
                            MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f),
                            RoundedCornerShape(12.dp)
                        )
                        .padding(16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Icon(
                            Icons.Default.Folder,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.outlineVariant,
                            modifier = Modifier.size(48.dp)
                        )
                        Spacer(modifier = Modifier.height(12.dp))
                        Text(
                            text = "点击添加文件 或 直接拖拽文件到这",
                            color = MaterialTheme.colorScheme.outlineVariant,
                            textAlign = TextAlign.Center
                        )
                    }
                }
            }
        }
    }


    // 文件选择对话框
    if (showDialog) {
        NativeFileSelectorDialog(
            onDismiss = { showDialog = false },
            onFilesSelected = { files ->
                //selectedFiles.clear()
                files.forEach {
                    if (!selectedFiles.contains(it)) {
                        selectedFiles.add(it)
//                        println("已选择文件 " + it.path)
                    }
                }
                showDialog = false
            }
        )
    }
}

// 单个文件项
@Composable
fun FileItem(file: File, onRemove: () -> Unit) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp)
    ) {
        // 文件图标
        Icon(
            Icons.Default.Attachment,
            contentDescription = null,
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(24.dp)
        )
        Spacer(modifier = Modifier.width(12.dp))

        // 文件信息
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = file.name,
                fontWeight = FontWeight.Medium,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = formatFileSize(file.length()),
                fontSize = 12.sp,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }

        // 移除按钮
        IconButton(
            onClick = onRemove,
            modifier = Modifier.size(24.dp)
        ) {
            Icon(
                Icons.Default.Close,
                contentDescription = "移除文件",
                tint = MaterialTheme.colorScheme.error
            )
        }
    }
}

// 文件大小格式化
private fun formatFileSize(size: Long): String {
    if (size < 1024) return "$size B"
    val kb = size / 1024
    if (kb < 1024) return "$kb KB"
    val mb = kb / 1024
    if (mb < 1024) return "%.2f MB".format(mb.toDouble())
    val gb = mb / 1024
    return "%.2f GB".format(gb.toDouble())
}

// 原生文件选择对话框

@Composable
fun NativeFileSelectorDialog(
    onDismiss: () -> Unit,
    onFilesSelected: (List<File>) -> Unit
) {
    val frame = remember { Frame() }
    val fileDialog = remember { FileDialog(frame, "选择文件", FileDialog.LOAD) }
    val scope = rememberCoroutineScope()
    var isLoading by remember { mutableStateOf(true) }

    LaunchedEffect(Unit) {
        // 在IO线程中显示文件对话框
        scope.launch(Dispatchers.IO) {
            try {
                fileDialog.isMultipleMode = true
                fileDialog.isVisible = true

                // 返回Swing UI线程处理结果
                withContext(Dispatchers.Swing) {
                    val files = fileDialog.files
                    if (files.isNotEmpty()) {
                        onFilesSelected(files.toList())
                    }
                    onDismiss()
                    frame.dispose()
                    isLoading = false
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Swing) {
                    onDismiss()
                    isLoading = false
                }
            }
        }
    }

    // 等待时显示进度指示器
    if (isLoading) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            CircularProgressIndicator()
        }
    }
}
